package com.happy.sky.common.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.buffer.Unpooled;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

/**
 * @name: TestNetty <tb>
 * @title: Netty 测试学习  <tb>
 * @author: cuixinfu@51play.com <tb>
 */
public class TestNetty {

    public static void main(String[] args) {
        ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT.directBuffer();//声明一个bytebuf 对象
        byteBuf.writeByte(1);//第一位置存放数字1（占用1个字节）
        byteBuf.writeShort(0);//第二位置存放数字 0（占用2个字节） ，这里是打算做长度
        String temp = "我是谁";//需要获取的数据
        byteBuf.writeBytes(temp.getBytes());//获取字节数组
        byteBuf.setShort(1,byteBuf.readableBytes());//设置第二位置的长度，也就是整个byteBuf对象的长度
        get(byteBuf);//get方法解析


        Charset utf8 = Charset.forName("UTF-8");
        ByteBuf buf = Unpooled.copiedBuffer("Netty in Action rocks!", utf8);     //1

        ByteBuf copy = buf.copy(0, 14);               //2
        System.out.println(copy.toString(utf8));      //3


        // 读取一个字符
        byte b = buf.readByte();
        System.out.println(asciiCodeToHel(b));

        buf.setByte(0, (byte) 'J');                   //4
        assert buf.getByte(0) != copy.getByte(0);

        // 读取三个字符
        ByteBuf byteBuf1 = buf.readBytes(3);
        System.out.println(byteBuf1.toString(utf8));

        // 读取字节数组
        byte[] timestamp = new byte[3];
        ByteBuf byteBuf2 = buf.readBytes(timestamp);
        System.out.println(byteBuf2.toString(utf8));

        //如果您不希望readerIndex更改：
        byte[] bytes = new byte[byteBuf2.readableBytes()];
        int readerIndex = byteBuf2.readerIndex();
        ByteBuf bytes1 = byteBuf2.getBytes(readerIndex, bytes);
        System.out.println(bytes1.toString(utf8));

    }

    /**
     * @title: ASCII 码转换字符和十六进制 <tb>
     * @author: cuixinfu@51play.com <tb>
     * @date: 2021/5/11 17:44<tb>
     */
    public static char asciiCodeToHel(byte asciiCode){
        char charStr = (char) Integer.parseInt("" + asciiCode);
        String hex = Integer.toHexString(asciiCode);
        System.out.println("ASCII码：" + asciiCode + ",显示汉字为：" + (char) Integer.parseInt("" + asciiCode) +",转换16进制：" + Integer.toHexString(asciiCode));
        return charStr;
    }

    public static void get(ByteBuf in){
        int inv = in.readerIndex();
        int first =in.getByte(inv);
        inv++;
        int length = in.getShort(inv);
        inv+=2;
        // 减3 是因为前面是获取到总长度，前面占用了byte + short = 1+2=3
        byte[] data = new byte[length - 3];//数据大小
        in.getBytes(inv, data);
        byte b = in.readByte();
        try {
            String str = new String(data, 0, data.length, "utf-8");
            System.out.println(str);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    public static void heapBuffer(){
        // 创建Java堆缓冲区
        ByteBuf heapBuf = Unpooled.buffer();
        if (heapBuf.hasArray()) { // 是数组支撑
            byte[] array = heapBuf.array();
            int offset = heapBuf.arrayOffset() + heapBuf.readerIndex();
            int length = heapBuf.readableBytes();
            handleArray(array, offset, length);
        }
    }

    private static void handleArray(byte[] array, int offset, int length) {
        Charset utf8 = Charset.forName("UTF-8");
        ByteBuf buf = Unpooled.copiedBuffer("Netty in Action rocks!", utf8);     //1

        ByteBuf copy = buf.copy(0, 14);               //2
        System.out.println(copy.toString(utf8));      //3

        buf.setByte(0, (byte) 'J');                   //4
        assert buf.getByte(0) != copy.getByte(0);

    }


}
